package logic

import (
	"context"
	"errors"
	"user-auth/models/cache"
	"user-auth/models/mysql"
	"user-auth/pkg"

	"user-auth/userrpc/internal/svc"
	"user-auth/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Mobile).Result()

	if result != in.CaptchaCode {
		return nil, errors.New("图形验证码错误，请重新输入")
	}

	result1, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()

	if result1 != in.SendCode {
		return nil, errors.New("短信验证码错误，请重新输入")
	}

	user := &mysql.User{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}

	if err := user.FindUserFirstOrCreat(mysql.DB, in.Mobile); err != nil {
		return nil, err
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误，请重新输入")
	}

	cache.Rdb.Del(l.ctx, "captcha"+in.Mobile)
	cache.Rdb.Del(l.ctx, "sendSms"+in.Mobile)

	return &userrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
